﻿using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Data;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Text;
using CommDll;
using System.Xml.Linq;
using System.Xml;
using System.Drawing;
using System.ComponentModel;
using DevComponents.DotNetBar.Controls;
namespace HospitalMedicineTraceability
{
    /// <summary>
    /// ClassName:frmQuery_EnterpriseCodeCheck
    /// Version:1.0
    /// Date:2019-06-23
    /// Author:seanouyang
    /// </summary>
    /// <remarks>
    /// 本类是一WinForm 窗体,本窗体主要为实现企业对码(先确定本地企业信息)
    /// </remarks>
    public partial class frmQuery_EnterpriseCodeCheck : DevComponents.DotNetBar.OfficeForm
    {
        #region 01 自定义属性
        public int m_nKind = 0; // 0:普通对码 1:指定对码(指定对码时用:本地订单)
        public Dictionary<string,string> m_dictInfo = new Dictionary<string,string>(); // 回传信息
        #endregion

        public frmQuery_EnterpriseCodeCheck()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 双缴存
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
  
        #region 02 自定义方法
        /// <summary>
        /// 初始化DataGridView字段显示信息
        /// </summary>
        public void _initDgvTitle()
        {
            string strFieldName = "", strFieldSql = "", strFieldWidth = "";
            // 1 主数据表格
            string strDgvName = this.Name + "_01" + '_' + m_nKind.ToString();
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strDgvName))
            {
                AppConfig._initDictField(strDgvName);
                //return;
            }
            // 默认值
            strFieldName = "ID-序号,Code-HIS配企编码,Name-HIS配企名称,TaxCode-配企编码,TaxName-配企名称,Linker-业务员,CodeCheckTime-对码时间";
            strFieldSql = "Id,Code,Name,TaxCode,TaxName,Linker,CodeCheckTime";
            strFieldWidth = "0,150,200,150,200,200,120";
            AppConfig.m_dictFieldName.Add(strDgvName, strFieldName);
            AppConfig.m_dictFieldSql.Add(strDgvName, strFieldSql);
            AppConfig.m_dictField0.Add(strDgvName, strFieldSql);
            AppConfig.m_dictFieldWidth0.Add(strDgvName, strFieldWidth);
            // 设置值
            strFieldSql = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strDgvName), AppConfig.m_dictField0[strDgvName]).Trim();
            AppConfig.m_dictField.Add(strDgvName, strFieldSql);
            strFieldWidth = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strDgvName), AppConfig.m_dictFieldWidth0[strDgvName]).Trim();
            AppConfig.m_dictFieldWidth.Add(strDgvName, strFieldWidth);
            // 02 右键双击设置显示方式
            this.dgvMain.Tag = strDgvName;
            this.dgvMain.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(DataDeal.dataGridView_MouseDoubleClick);
            // 03 其他事件
            this.dgvMain.ColumnHeaderMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(CommFun._dgvColumnHeaderSort);// 排序
            this.dgvMain.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(CommFun._dgvRowEnter);// 改变行颜色           
            // 2 明细数据表格
            strDgvName = this.Name + "_02" + '_' + m_nKind.ToString();
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strDgvName))
            {
                AppConfig._initDictField(strDgvName);
                //return;
            }
            // 默认值
            strFieldName = "SupplierCode-配企编码,SupplierName-配企名称,Linker-业务员";
            strFieldSql = "SupplierCode,SupplierName";
            strFieldWidth = "150,200";
            AppConfig.m_dictFieldName.Add(strDgvName, strFieldName);
            AppConfig.m_dictFieldSql.Add(strDgvName, strFieldSql);
            AppConfig.m_dictField0.Add(strDgvName, strFieldSql);
            AppConfig.m_dictFieldWidth0.Add(strDgvName, strFieldWidth);
            // 设置值
            strFieldSql = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strDgvName), AppConfig.m_dictField0[strDgvName]).Trim();
            AppConfig.m_dictField.Add(strDgvName, strFieldSql);
            strFieldWidth = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strDgvName), AppConfig.m_dictFieldWidth0[strDgvName]).Trim();
            AppConfig.m_dictFieldWidth.Add(strDgvName, strFieldWidth);
            // 02 右键双击设置显示方式
            this.dgvDetail.Tag = strDgvName;
            this.dgvDetail.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(DataDeal.dataGridView_MouseDoubleClick);
            // 03 其他事件
            this.dgvDetail.ColumnHeaderMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(CommFun._dgvColumnHeaderSort);// 排序
            this.dgvDetail.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(CommFun._dgvRowEnter);// 改变行颜色
        }

        /// <summary>
        /// 查询信息(配企His)
        /// </summary>
        private void _querySupplierHis()
        {
            string strWhere = "";
            string strTemp = "";
            try
            {
                // 01 取条件
                // 0101 通用条件
                strTemp = txtWhereSupplierHis.Text.Trim();
                if (!strTemp.Equals("") && (cbWhere01.Checked || cbWhere02.Checked))
                {
                    strTemp = "";
                    if (cbWhere01.Checked)
                    {
                        strTemp = (strTemp.Equals("") ? "" : " or ") + string.Format("(Code like '%{0}%' or TaxCode like '%{0}%')", txtWhereSupplierHis.Text.Trim());
                    }
                    if (cbWhere02.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("(Name like '%{0}%' or TaxName like '%{0}%')", txtWhereSupplierHis.Text.Trim());
                    }
                    strWhere = (strWhere.Equals("") ? "" : " and ") + string.Format("({0})", strTemp);
                }
                // 0102 对码状态
                strTemp = "";
                if (cbState0.Checked || cbState1.Checked || cbState.Checked) {
                    if (cbState0.Checked)
                    {
                        strTemp = (strTemp.Equals("") ? "" : " or ") + string.Format("isnull(CodeCheckStatus,'未对码') = '{0}' ", "未对码");
                    }
                    if (cbState1.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("CodeCheckStatus = '{0}' ", "已对码");
                    }
                    if (cbState.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("CodeCheckStatus = '{0}' ", "暂不对码");
                    }
                    strWhere = (strWhere.Equals("") ? "" : " and ") + string.Format("({0})", strTemp);
                }
                strWhere = (strWhere.Equals("") ? "" : " where ") + string.Format("{0}", strWhere);

                // 03 取数据
                string strSql = string.Format("SELECT top 1000 {0} FROM TH_Supplier {{0}} order by ID", AppConfig.m_dictFieldSql[dgvMain.Tag.ToString()]); 
                strSql = string.Format(strSql, strWhere);
                DataTable dt = AppInfo._openSql_DataTable(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    // 04 显示数据
                    // 0401 调整字段顺序
                    CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[dgvMain.Tag.ToString()]);
                    // 0402 显示数据
                    CommFun._showDataGridView(dgvMain, dt, AppConfig.m_dictFieldWidth[dgvMain.Tag.ToString()], AppConfig.m_dictFieldName[dgvMain.Tag.ToString()]);
                    // 0403 显示明细数据
                    dgv0_CellClick(dgvMain, new DataGridViewCellEventArgs(dgvMain.Columns["Name"].Index, 0));
                }
                else
                {
                    // 清除数据
                    DataTable dtTemp = (DataTable)dgvMain.DataSource;
                    if (dtTemp != null && dtTemp.Rows.Count > 0)
                    {
                        dtTemp.Rows.Clear();
                    }
                    dtTemp = (DataTable)dgvDetail.DataSource;
                    if (dtTemp != null && dtTemp.Rows.Count > 0)
                    {
                        dtTemp.Rows.Clear();
                    }
                    txtWhereSupplier.Text = "";
                }
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }         
        }

        /// <summary>
        /// 查询配企
        /// </summary>
        private void _querySupplier()
        {
            try
            {
                // 01 条件1
                string strWhere = "", strTemp = "";
                string strTemp1 = txtWhereSupplier.Text.Trim();
                if (!strTemp1.Equals("") && (cbWhere11.Checked || cbWhere12.Checked))
                {
                    if (cbWhere11.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("SupplierCode like '%{0}%' ", strTemp1);
                    }
                    if (cbWhere12.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("SupplierName like '%{0}%' ", strTemp1);
                    }
                    strWhere = string.Format(" Where  ({0})", strTemp);
                }
                // 03 取数据
                string strSql = "select {0} from (SELECT SupplierCode = SalerCode,SupplierName = SalerName FROM TH_Invoice group by SalerCode,SalerName) A {1} order by SupplierCode";
                strSql = string.Format(strSql, AppConfig.m_dictFieldSql[dgvDetail.Tag.ToString()], strWhere);
                DataTable dt = AppInfo._openSql_DataTable(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    // 04 显示数据
                    // 0401 调整字段顺序
                    CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[dgvDetail.Tag.ToString()]);
                    // 0402 显示数据
                    CommFun._showDataGridView(dgvDetail, dt, AppConfig.m_dictFieldWidth[dgvDetail.Tag.ToString()], AppConfig.m_dictFieldName[dgvDetail.Tag.ToString()]);
                }
                else
                {
                    // 清除数据
                    DataTable dtTemp = (DataTable)dgvDetail.DataSource;
                    if (dtTemp != null && dtTemp.Rows.Count > 0)
                    {
                        dtTemp.Rows.Clear();
                    }
                }
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }
        }

        /// <summary>
        /// 清除匹配信息
        /// </summary>
        private void _clearCustomerInfo1()
        {
            txtWhereSupplier.Text = "";
            if (dgvDetail.Rows.Count > 0)
            {
                ((DataTable)dgvDetail.DataSource).Rows.Clear();
            }
        }

        /// <summary>
        /// 药品对码
        /// </summary>
        private void _checkCode()
        {
            if (dgvMain.CurrentRow == null)
            {
                CommFun._messageBoxShow("请先确定HIS数据！");
                return;
            }
            try
            {
                frmSupplierCodeCheck frm = new frmSupplierCodeCheck();
                // 联系人处理
                // 01 取联系人(当新的配企与原配企不相同时，去除原配企联系人)
                if (!ModelSupplierCodeCheck.strSupplierCode.Equals(ModelSupplierCodeCheck.strCode1))
                {
                    ModelSupplierCodeCheck.strLinkman0 = "";
                }                

                frm.m_dictInfo.Add("SupplierCode_His", dgvMain.CurrentRow.Cells["Code"].Value.ToString());
                frm.m_dictInfo.Add("SupplierName_His", dgvMain.CurrentRow.Cells["Name"].Value.ToString());
                frm.m_dictInfo.Add("SupplierCode", dgvDetail.CurrentRow.Cells["SupplierCode"].Value.ToString());
                frm.m_dictInfo.Add("SupplierName", dgvDetail.CurrentRow.Cells["SupplierName"].Value.ToString());

                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (m_nKind == 1)
                    {
                        // 需返回信息
                        m_dictInfo.Add("SupplierCode", ModelSupplierCodeCheck.strCode1);
                        m_dictInfo.Add("SupplierName", ModelSupplierCodeCheck.strName1);
                        DialogResult = DialogResult.OK;
                    }
                    else {
                        // 更新数据
                        dgvMain.Rows[dgvMain.CurrentRow.Index].Cells["TaxCode"].Value = ModelSupplierCodeCheck.strCode1;
                        dgvMain.Rows[dgvMain.CurrentRow.Index].Cells["TaxName"].Value = ModelSupplierCodeCheck.strName1;
                        dgvMain.Rows[dgvMain.CurrentRow.Index].Cells["Linker"].Value = ModelSupplierCodeCheck.strLinkman0;
                        dgvMain.Rows[dgvMain.CurrentRow.Index].Cells["CodeCheckTime"].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        ModelSupplierCodeCheck.strSupplierCode = ModelSupplierCodeCheck.strCode1; 
                    }
                }
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }
        }
        #endregion

        #region 03 窗体相关事件方法
        private void frmQuery_EnterpriseCodeCheck_Load(object sender, EventArgs e)
        {
            timerInit.Enabled = true;
            // 初始化DataGridView
            _initDgvTitle();
            // splitContainer1
            dgvMain.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top
                    | System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom));
            splitContainer1.Tag = this.Name + "_splitContainerHeight";
            splitContainer1.SplitterDistance = FunctionComm._strToInt(AppConfig.m_iniSetup._readValue("Common", splitContainer1.Tag.ToString(), splitContainer1.SplitterDistance.ToString()).Trim(), splitContainer1.SplitterDistance);
            splitContainer1.SplitterMoved += DataDeal.splitContainer_SplitterMoved; 
        }
        private void timerInit_Tick(object sender, EventArgs e)
        {
            timerInit.Enabled = false;            
            // 指定配企信息对码使用
            if (m_nKind == 1)
            {
                // 赋默认值
                gbInfo0.Text = "HIS配企信息";
                txtWhereSupplierHis.Text = m_dictInfo["SupplierCode"];
                txtWhereSupplierHis.ReadOnly = true;
                cbWhere01.Checked = true;
                cbWhere01.Enabled = false;
                cbWhere02.Checked = false;
                cbWhere02.Enabled = false;
                cbState.Enabled = false;
                cbState0.Enabled = false;
                cbState1.Enabled = false;
                // 取数据
                btnQuerySupplierHis_Click(null, null);
            }
        }

        private void btnQuerySupplierHis_Click(object sender, EventArgs e)
        {
            _querySupplierHis();
        }
        
        private void btnQuerySupplier_Click(object sender, EventArgs e)
        {
            _querySupplier();
        }
        private void txtWhere0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnQuerySupplierHis_Click(null, null);
            }
        }

        private void txtWhere1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnQuerySupplier_Click(null, null);
            }
        }        
        #endregion

        #region 04 DataGridView 事件方法

        private void dgv0_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 取匹配数据
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }

            DataGridView dgv = (DataGridView)sender;
            // 取His数据
            ModelSupplierCodeCheck.strID0 = dgv.Rows[e.RowIndex].Cells["ID"].Value.ToString();
            ModelSupplierCodeCheck.strCode0 = dgv.Rows[e.RowIndex].Cells["Code"].Value.ToString();
            ModelSupplierCodeCheck.strName0 = dgv.Rows[e.RowIndex].Cells["Name"].Value.ToString();
            ModelSupplierCodeCheck.strLinkman0 = dgv.Rows[e.RowIndex].Cells["Linker"].Value.ToString();
            ModelSupplierCodeCheck.strSupplierCode = dgv.Rows[e.RowIndex].Cells["TaxCode"].Value.ToString();
            
            // 按指定列名信息查询数据
            string strTemp = dgv.Columns[e.ColumnIndex].Name;
            cbWhere11.Checked = false;
            cbWhere12.Checked = false;
            if ("Code,TaxCode,Name,TaxName".Contains(strTemp))
            {
                switch (strTemp)
                {
                    case "Code":
                    case "TaxCode":
                        cbWhere11.Checked = true;
                        break;
                    case "Name":
                    case "TaxName":
                        cbWhere12.Checked = true;
                        break;
                }
                txtWhereSupplier.Text = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                btnQuerySupplier_Click(null, null);
            }
            else
            {
                _clearCustomerInfo1();
            }
        }

        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // 双击对码操作
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }
            DataGridView dgv = (DataGridView)sender;
            switch (dgv.Name)
            {
                case "dgvMain":
                    // 对码操作:设置“暂不对码”
                    if (m_nKind != 1)
                    {
                        if (CommFun._messageBoxShow("确认设置成【暂不对码】？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                        {
                            try
                            {
                                ModelSupplierCodeCheck.strCode1 = "暂不对码";
                                ModelSupplierCodeCheck.strName1 = "";
                                ModelSupplierCodeCheck._saveInfo();
                                // 更新数据
                                dgv.CurrentRow.Cells["TaxCode"].Value = ModelSupplierCodeCheck.strCode1;
                                dgv.CurrentRow.Cells["TaxName"].Value = ModelSupplierCodeCheck.strName1;                                
                            }
                            catch (Exception ex)
                            {
                                CommFun._messageBoxShow(ex.Message);
                                return;
                            }
                        }
                    }
                    break;
                case "dgvDetail":
                    // 初始化匹配信息
                    ModelSupplierCodeCheck.strCode1 = dgv.Rows[e.RowIndex].Cells["SupplierCode"].Value.ToString();
                    ModelSupplierCodeCheck.strName1 = dgv.Rows[e.RowIndex].Cells["SupplierName"].Value.ToString();
                    // 对码
                    _checkCode();
                    break;
            }
        }
        #endregion
    }
}


